import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/model/device_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/battery_cell_tree/battery_cell_tree_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/battery_pack_detail/components/bmu_bar_chart.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/new_air_cooling_page_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

/**
 *
 * @Description TODO
 * @Author liuer
 * @CreateTime 2024年01月15日 09:47
 */
class BatteryCluster extends StatefulWidget {
  final DeviceModel deviceModel;
  final BatteryCellTreeModel? cluster;
  // 控制更多弹窗控制器
  final BrnCloseWindowController closeController;

  /// 为false，时关闭弹窗
  final bool isShow;
  const BatteryCluster(this.cluster, this.deviceModel, this.closeController,
      {super.key, required this.isShow});

  @override
  State<BatteryCluster> createState() => _BatteryClusterState();
}

class _BatteryClusterState extends State<BatteryCluster>
    with TickerProviderStateMixin {
  UseSubsribe subsribe = UseSubsribe();

  /// 电池单体tab
  List<BadgeTab>? tabs;

  late TabController tabController;

  //ListView 的 滚动控制器
  ScrollController scrollController = ScrollController();

  StreamController<Map<String, dynamic>>? streamController;

  /// 请求方法
  late DeviceServices services;

  Map<int, DeviceModel?>? bmuMap;

  Map<int, int> tabNumMap = {
    ProductIDType.newLiquidCoolingEnergyBattery.value: 5,
    ProductIDType.liquidEnergyBatteryStack.value: 5,
    ProductIDType.liquidEnergy232BatteryPack.value: 5,
    ProductIDType.pvEnergyBms.value: 9
  };

  int activBmuIndex = 0;
  @override
  void initState() {
    services = Get.put<DeviceServices>(DeviceServices());

    getBmus();

    if (widget.cluster != null) {
      streamController = subsribe.start([widget.cluster!.deviceId!], true);
    }
    scrollController.addListener(() {
      widget.closeController.closeMoreWindow();
    });
    super.initState();
  }

  @override
  void didUpdateWidget(covariant BatteryCluster oldWidget) {
    if (widget.isShow != oldWidget.isShow) {
      if (!widget.isShow) {
        widget.closeController.closeMoreWindow();
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void deactivate() {
    Log.d('deactivate');

    super.deactivate();
  }

  @override
  void dispose() async {
    // 关闭流
    tabController.dispose();
    subsribe.closeListen();

    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Log.d('context===' + widget.isShow.toString());
    if (!widget.isShow) {
      widget.closeController.closeMoreWindow();
    }
    return GetBuilder<NewAirCoolingPageController>(
        builder: (_) => WillPopScope(
              onWillPop: () async {
                widget.closeController.closeMoreWindow();
                return true;
              },
              child: GestureDetector(
                onTap: () {
                  widget.closeController.closeMoreWindow();
                },
                child: StreamBuilder(
                  builder: (context, snapshot) => ListView(
                    controller: scrollController,
                    shrinkWrap: true,
                    padding: EdgeInsets.only(bottom: 10.h),
                    children: [
                      // DeviceUtil.blockContainer(Column(
                      //   crossAxisAlignment: CrossAxisAlignment.start,
                      //   children: [
                      //     DeviceUtil.headTitle(''),
                      //   ],
                      // )),
                      if (bmuMap != null) ...{
                        BrnTabBar(
                          tabs: tabs,
                          controller: tabController,
                          tabWidth: 65.w,
                          showMore: true,
                          closeController: widget.closeController,
                          onTap: (state, index) =>
                              widget.closeController.closeMoreWindow(),
                        ),
                        SizedBox(
                            height: 300,
                            child: BmuBarChart(
                                bmuMap![activBmuIndex + 1]?.deviceId,
                                widget.deviceModel.productId)),
                      }
                    ],
                  ),
                  stream: null,
                ),
              ),
            ));
  }

  getBmus() async {
    try {
      showLoading(toast: ResKey.loading.tr);
      List data = await services
          .getSubDevices({'parentId': widget.deviceModel.deviceId});
      if (FuncUtils.isListEmpty(data)) {
        data = List.generate(
            tabNumMap[widget.deviceModel.productId] ?? 10, (index) => null);
      }
      List tempList = [];
      List dataMap = [];
      Log.d('data===' + data.toString());

      ///进行一次遍历,删除重复的sn
      for (var element in data) {
        if (element != null && !tempList.contains(element['sn'])) {
          tempList.add(element['sn']);
          dataMap.add(element);
        }
      }
      Log.d('dataMap===' + dataMap.toString());
      Map<int, DeviceModel?> maps = {};
      for (var i = 0; i < dataMap.length; i++) {
        maps.putIfAbsent(i + 1,
            () => dataMap[i] == null ? null : DeviceModel.fromJson(dataMap[i]));
      }
      tabs = List.generate(
          dataMap.length,
          (index) => BadgeTab(
                text: 'BMU${index + 1}',
              ));
      tabController = TabController(length: dataMap.length, vsync: this);
      tabController.addListener(
        () {
          activBmuIndex = tabController.index;
          if (mounted) {
            setState(() {});
          }
        },
      );
      setState(() {
        bmuMap = maps;
      });
    } on ApiException catch (e) {
      handleException(e);
    } finally {
      dismissLoading();
    }
  }
}
